<template>
  <div class="post-detail-container">
    <a-spin :spinning="loading">
      <div v-if="post" class="post-content-wrapper">
        <a-row :gutter="24">
          <!-- 左侧导航 -->
          <a-col :xs="24" :lg="6">
            <div class="sidebar left-sidebar sticky-sidebar">
              <!-- 博客分类 -->
              <a-card title="博客分类" class="categories-card">
                <div class="categories-list">
                  <a-empty v-if="categories.length === 0" description="暂无分类" />
                  <a-menu v-else mode="inline" :selected-keys="selectedCategoryKeys">
                    <a-menu-item 
                      v-for="category in categories" 
                      :key="category.id"
                      @click="viewCategory(category.id)"
                    >
                      <span class="category-item">
                        {{ category.name }}
                        <span class="category-count">({{ category.postCount || 0 }})</span>
                      </span>
                    </a-menu-item>
                  </a-menu>
                </div>
              </a-card>

              <!-- 最新文章 -->
              <a-card title="最新文章" class="recent-posts-card">
                <div class="recent-posts-list">
                  <a-empty v-if="recentPosts.length === 0" description="暂无文章" />
                  <div 
                    v-else
                    v-for="recentPost in recentPosts" 
                    :key="recentPost.id"
                    class="recent-post-item"
                    @click="viewPost(recentPost.id)"
                  >
                    <h4 class="recent-post-title">{{ recentPost.title }}</h4>
                    <div class="recent-post-meta">
                      <span class="post-date">{{ formatDate(recentPost.createdAt) }}</span>
                    </div>
                  </div>
                </div>
              </a-card>
            </div>
          </a-col>

          <!-- 中间内容 -->
          <a-col :xs="24" :lg="12">
            <div class="post-content">
              <!-- 文章标题 -->
              <h1 class="post-title">{{ post.title }}</h1>
              
              <!-- 作者信息 -->
              <div class="post-meta">
                <div class="author-info">
                  <a-avatar :src="post.author?.avatar" :size="40">
                    {{ post.author?.nickname?.charAt(0) || 'U' }}
                  </a-avatar>
                  <div class="author-details">
                    <span class="author-name">{{ post.author?.nickname || '匿名用户' }}</span>
                    <span class="post-date">{{ formatDate(post.createdAt) }}</span>
                  </div>
                </div>
                
                <!-- 只有登录用户且是文章作者才能看到编辑和删除按钮 -->
                <div class="post-actions" v-if="userStore.isLoggedIn && userStore.userInfo?.id === post.userId">
                  <a-button @click="editPost">编辑</a-button>
                  <a-button type="primary" danger @click="deletePost">删除</a-button>
                </div>
              </div>
              
              <!-- 文章统计数据 -->
              <PostStats v-if="post.id" :post-id="post.id" />
              
              <!-- 文章封面 -->
              <div v-if="post.coverImage" class="post-cover">
                <img :src="post.coverImage" :alt="post.title" />
              </div>
              
              <!-- 文章内容 -->
              <div class="post-body" v-html="formatContent(post.content)"></div>
              
              <!-- 文章标签 -->
              <div v-if="post.tags && post.tags.length > 0" class="post-tags">
                <a-tag 
                  v-for="tag in post.tags" 
                  :key="tag.id" 
                  :color="tag.color || 'blue'"
                  class="tag-item"
                  @click="viewTag(tag.id)"
                >
                  {{ tag.name }}
                </a-tag>
              </div>
              
              <!-- 评论区域 -->
              <CommentList v-if="post.id" :post-id="post.id" />
            </div>
          </a-col>

          <!-- 右侧边栏 -->
          <a-col :xs="24" :lg="6">
            <div class="sidebar right-sidebar sticky-sidebar">
              <!-- 用户信息卡片 -->
              <a-card v-if="userStore.isLoggedIn" title="个人信息" class="user-card">
                <div class="user-info">
                  <a-avatar 
                    :src="userStore.userInfo?.avatar" 
                    :size="64"
                    class="user-avatar"
                  >
                    {{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
                  </a-avatar>
                  <div class="user-details">
                    <h4>{{ userStore.userInfo?.nickname }}</h4>
                    <p>{{ userStore.userInfo?.email }}</p>
                    <a-button 
                      type="link" 
                      size="small"
                      @click="$router.push('/profile')"
                    >
                      查看个人中心
                    </a-button>
                  </div>
                </div>
              </a-card>
              
              <!-- 登录提示卡片 -->
              <a-card v-else title="欢迎访问" class="login-prompt-card">
                <div class="login-prompt-content">
                  <p>登录后享受更多互动功能：</p>
                  <ul>
                    <li>👍 点赞文章和评论</li>
                    <li>💬 发表评论和回复</li>
                    <li>🔖 收藏喜欢的文章</li>
                    <li>🔔 接收个性化通知</li>
                  </ul>
                  <a-button type="primary" block @click="$router.push('/login')">
                    立即登录
                  </a-button>
                  <div class="register-link">
                    还没有账号？<a @click="$router.push('/register')">立即注册</a>
                  </div>
                </div>
              </a-card>

              <!-- 近期评论 -->
              <a-card title="近期评论" class="recent-comments-card">
                <div class="recent-comments-list">
                  <a-empty v-if="recentComments.length === 0" description="暂无评论" />
                  <div 
                    v-else
                    v-for="comment in recentComments" 
                    :key="comment.id"
                    class="comment-item"
                  >
                    <div class="comment-author">
                      <a-avatar :size="24" :src="comment.author?.avatar">
                        {{ comment.author?.nickname?.charAt(0) || 'U' }}
                      </a-avatar>
                      <span class="comment-author-name">{{ comment.author?.nickname || '匿名用户' }}</span>
                    </div>
                    <div class="comment-content">{{ comment.content }}</div>
                    <div class="comment-meta">
                      <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
                    </div>
                  </div>
                </div>
              </a-card>
            </div>
          </a-col>
        </a-row>
      </div>
      
      <div v-else class="empty-state">
        <a-empty description="文章不存在或已被删除" />
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores'
import { postApi, likeApi, commentApi, categoryApi } from '@/api'
import type { Post, Comment, Category } from '@/types'
import PostStats from './PostStats.vue'
import CommentList from './CommentList.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const postId = Number(route.params.id)

// 检查postId是否有效
if (!postId || isNaN(postId)) {
  message.error('文章ID无效')
  router.push('/')
}

// 响应式数据
const loading = ref(false)
const post = ref<Post | null>(null)
const relatedPosts = ref<Post[]>([])
const recentComments = ref<Comment[]>([])
const recentPosts = ref<Post[]>([])
const categories = ref<Category[]>([])
const selectedCategoryKeys = ref<string[]>([])

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化内容
const formatContent = (content?: string) => {
  if (!content) return ''
  return content.replace(/\n/g, '<br>')
}

// 编辑文章
const editPost = () => {
  router.push(`/edit/${post.value?.id}`)
}

// 删除文章
const deletePost = async () => {
  if (!post.value) return
  
  try {
    await postApi.deletePost(post.value.id)
    message.success('文章已删除')
    router.push('/')
  } catch (error) {
    message.error('删除文章失败')
  }
}

// 查看文章详情
const viewPost = (id: number) => {
  router.push(`/post/${id}`)
}

// 查看分类
const viewCategory = (categoryId: number) => {
  router.push(`/category/${categoryId}`)
}

// 查看标签
const viewTag = (tagId: number) => {
  router.push(`/tag/${tagId}`)
}

// 加载文章数据
const loadPostData = async () => {
  // 检查postId是否有效
  if (!postId || isNaN(postId)) {
    post.value = null
    return
  }

  loading.value = true
  
  try {
    // 获取文章详情
    const response = await postApi.getPostDetail(postId)
    post.value = response.data
    
    // 增加浏览量
    try {
      await postApi.incrementViewCount(postId)
      // 更新文章浏览量
      if (post.value) {
        post.value.viewCount = (post.value.viewCount || 0) + 1
      }
    } catch (error) {
      console.warn('增加浏览量失败:', error)
    }
    
    // 并行获取相关文章、近期评论、分类和最新文章
    await Promise.allSettled([
      // 获取相关文章（这里模拟获取同分类的文章）
      postApi.getPostList({
        pageNo: '1',
        pageSize: '3',
        keyword: '',
        status: 'PUBLISHED',
        categoryId: post.value?.categoryId?.toString() || '',
        tagId: '',
        orderBy: 'createdAt',
        asc: 'false'
      }),
      // 获取近期评论
      commentApi.getCommentTree(0), // 获取所有评论
      // 获取分类列表
      categoryApi.getCategoryList({ page: '1', size: '10' }),
      // 获取最新文章
      postApi.getPostList({
        pageNo: '1',
        pageSize: '5',
        keyword: '',
        status: 'PUBLISHED',
        categoryId: '',
        tagId: '',
        orderBy: 'createdAt',
        asc: 'false'
      })
    ]).then(([relatedResponse, commentsResponse, categoriesResponse, recentPostsResponse]) => {
      // 处理相关文章
      if (relatedResponse.status === 'fulfilled') {
        relatedPosts.value = relatedResponse.value.data.result?.filter((p: Post) => p.id !== postId) || []
      }
      
      // 处理近期评论
      if (commentsResponse.status === 'fulfilled') {
        // 取最新的3条评论
        recentComments.value = [...commentsResponse.value.data].slice(0, 3)
      }
      
      // 处理分类
      if (categoriesResponse.status === 'fulfilled') {
        categories.value = categoriesResponse.value.data.result || []
      }
      
      // 处理最新文章
      if (recentPostsResponse.status === 'fulfilled') {
        recentPosts.value = recentPostsResponse.value.data.result?.filter((p: Post) => p.id !== postId) || []
      }
    })
  } catch (error: any) {
    console.error('加载文章数据失败:', error)
    post.value = null
    // 如果是文章不存在的错误，显示友好的提示
    if (error?.response?.status === 404) {
      message.error('文章不存在或已被删除')
    } else {
      message.error('加载文章数据失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadPostData()
})
</script>

<style scoped>
.post-detail-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  background: #f0f8ff;
}

.post-content-wrapper {
  width: 100%;
}

.post-content {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
}

.post-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 24px 0;
  line-height: 1.3;
  color: #262626;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  color: #262626;
}

.post-date {
  font-size: 14px;
  color: #8c8c8c;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.post-cover {
  margin: 32px 0;
}

.post-cover img {
  width: 100%;
  border-radius: 8px;
}

.post-body {
  margin-bottom: 32px;
  line-height: 1.8;
  font-size: 16px;
  color: #262626;
}

.post-body :deep(h2) {
  font-size: 24px;
  font-weight: 600;
  margin: 32px 0 16px 0;
  color: #262626;
}

.post-body :deep(h3) {
  font-size: 20px;
  font-weight: 600;
  margin: 24px 0 12px 0;
  color: #262626;
}

.post-body :deep(p) {
  margin: 16px 0;
}

.post-body :deep(ul) {
  margin: 16px 0;
  padding-left: 24px;
}

.post-body :deep(li) {
  margin: 8px 0;
}

.post-body :deep(pre) {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 16px 0;
}

.post-body :deep(code) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
}

.post-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 32px;
}

.tag-item {
  cursor: pointer;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 添加sticky定位实现悬浮吸顶效果 */
.sticky-sidebar {
  position: sticky;
  top: 80px;
  align-self: flex-start;
}

.left-sidebar .categories-card,
.left-sidebar .recent-posts-card,
.right-sidebar .recent-comments-card,
.right-sidebar .user-card,
.right-sidebar .login-prompt-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
}

.categories-list {
  max-height: 300px;
  overflow-y: auto;
}

.category-item {
  display: flex;
  justify-content: space-between;
}

.category-count {
  color: #8c8c8c;
  font-size: 12px;
}

.recent-posts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recent-post-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.recent-post-item:last-child {
  border-bottom: none;
}

.recent-post-title {
  font-size: 14px;
  font-weight: 500;
  margin: 0 0 4px 0;
  color: #262626;
  line-height: 1.4;
}

.recent-post-meta {
  font-size: 12px;
  color: #8c8c8c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.recent-comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.comment-author-name {
  font-size: 13px;
  font-weight: 500;
  color: #595959;
}

.comment-content {
  font-size: 13px;
  color: #262626;
  line-height: 1.4;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.comment-meta {
  font-size: 12px;
  color: #8c8c8c;
}

.user-card .user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
}

.user-details p {
  margin: 0 0 8px 0;
  color: #8c8c8c;
  font-size: 14px;
}

.login-prompt-card .login-prompt-content ul {
  padding-left: 20px;
  margin: 12px 0;
}

.login-prompt-card .login-prompt-content li {
  margin: 8px 0;
  font-size: 14px;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
}

.register-link a {
  color: #1890ff;
  cursor: pointer;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .post-detail-container {
    padding: 16px;
  }
  
  .post-title {
    font-size: 24px;
  }
  
  .post-meta {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .post-stats {
    flex-wrap: wrap;
  }
  
  .post-content {
    padding: 20px;
  }
  
  .comment-form {
    padding: 16px;
  }
  
  /* 在小屏幕上禁用sticky效果 */
  .sticky-sidebar {
    position: static;
  }
}
</style>